import 'dart:convert';

import 'package:du_application/http/HttpUtil.dart';
import 'package:du_application/http/Options.dart';

import 'package:du_application/model/AuthModel.dart';
import 'package:du_application/pages/HomePage.dart';
import 'package:du_application/pages/login/registerCode.dart';
import 'package:du_application/provide/AuthProvider.dart';
import 'package:du_application/routes/application.dart';

import 'package:du_application/units/iconfont.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:provide/provide.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:video_player/video_player.dart';
import 'package:common_utils/common_utils.dart';

class Login extends StatefulWidget {
  final String go;
  const Login({this.go});
  @override
  _LoginState createState() => _LoginState();
}

class _LoginState extends State<Login> {
   Future<SharedPreferences> _prefs = SharedPreferences.getInstance();
 


  void _saveString(String str,String name) async {
    var ins = await _prefs;
    ins.setString(name,str);
  }
   _getString(String name) async {
    var ins = await _prefs;
   return  ins.getString(name);
  }
  //焦点
  FocusNode _focusNodeUserName = new FocusNode();
  FocusNode _focusNodePassWord = new FocusNode();
  TextEditingController _userNameController = new TextEditingController();

  GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  GlobalKey<FormState> _loginKey = GlobalKey<FormState>();
  var _password = ''; //用户名
  var _username = ''; //密码
  var _code = ''; //密码
  bool isReg = true;
  // 声明视频控制器

  bool phoneIsYes = false;
  bool passwordIsYes = false;
  bool repasswordIsYes = false;

  VideoPlayerController _controller;
  //
  final String videoUrl = "https://qiniu-xpc4.xpccdn.com/5eb663f53e8d6.mp4";

  @override
  void initState() {
    super.initState();
    _focusNodeUserName.addListener(_focusNodeListener);
    _focusNodePassWord.addListener(_focusNodeListener);
    _controller = VideoPlayerController.network(videoUrl)
      ..initialize().then((_) {
        setState(() {});
        _controller.play();
        _controller.setLooping(true);
        _controller.setVolume(0);
        // _controller.setVolume(0.0);
        // Timer.periodic(Duration(seconds: 15), (Timer time) {
        //   print(time);
        // });
      });
  }

  @override
  void dispose() {
    _controller.pause();
    _focusNodeUserName.removeListener(_focusNodeListener);
    _focusNodePassWord.removeListener(_focusNodeListener);
    _userNameController.dispose();

    super.dispose();
  }

  Future<Null> _focusNodeListener() async {
    if (_focusNodeUserName.hasFocus) {
      print("用户名框获取焦点");
      // 取消密码框的焦点状态
      _focusNodePassWord.unfocus();
    }
    if (_focusNodePassWord.hasFocus) {
      print("密码框获取焦点");
      // 取消用户名框焦点状态
      _focusNodeUserName.unfocus();
    }
  }

  @override
  Widget build(BuildContext context) {
    return _controller.value.initialized
        ? Scaffold(
            body: Stack(
            fit: StackFit.expand,
            children: <Widget>[
              Transform.scale(
                scale: _controller.value.aspectRatio /
                    MediaQuery.of(context).size.aspectRatio *
                    1.01,
                child: Center(
                  child: Container(
                    height: MediaQuery.of(context).size.height,
                    width: MediaQuery.of(context).size.width,
                    child: AspectRatio(
                      aspectRatio: _controller.value.aspectRatio,
                      child: VideoPlayer(
                        _controller,
                      ),
                    ),
                  ),
                ),
              ),
              Positioned(
                  left: ScreenUtil().setWidth(10),
                  top: ScreenUtil().setWidth(10),
                  child: IconButton(
                    icon: Icon(
                      Icons.close,
                      color: Colors.white,
                    ),
                    onPressed: () {
                      Navigator.of(context).pop();
                    },
                  )),
              Positioned(
                width: MediaQuery.of(context).size.width,
                top: 80.0,
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    Icon(IconFont.icon_duowei,
                        color: Colors.white, size: ScreenUtil().setSp(160)),
                    SizedBox(
                      height: ScreenUtil().setHeight(120),
                    ),
                    Offstage(
                      offstage: isReg,
                      child: Container(
                          padding: EdgeInsets.symmetric(
                              horizontal: ScreenUtil().setWidth(20),
                              vertical: ScreenUtil().setWidth(20)),
                          width: ScreenUtil().setWidth(860),
                          color: Color.fromRGBO(255, 255, 255, 0.7),
                          child: Form(
                              key: _formKey,
                              child: Column(
                                children: <Widget>[
                                  TextFormField(
                                    textInputAction: TextInputAction.done,
                                    keyboardType: TextInputType.number,
                                    // obscureText: true,
                                    validator: validateUserName,
                                    style: TextStyle(
                                        color: phoneIsYes
                                            ? Colors.black
                                            : Colors.red),
                                    onChanged: (String input) {
                                      setState(() {
                                        _username = input;
                                        phoneIsYes =
                                            RegexUtil.isMobileExact(input);
                                      });
                                    },
                                    onSaved: (String value) {
                                      _username = value;
                                    },
                                    inputFormatters:[WhitelistingTextInputFormatter.digitsOnly],//只允许输入数字
                                    focusNode: _focusNodeUserName,
                                    decoration: InputDecoration(
                                        border: InputBorder.none,
                                        labelText: '手机号',
                                        focusColor: Colors.black,
                                        focusedBorder: InputBorder.none,
                                        prefixIcon: Icon(Icons.phone)),
                                  ),
                                  TextFormField(
                                    textInputAction: TextInputAction.done,
                                    //  keyboardType:TextInputType.,
                                    obscureText: true,
                                    onSaved: (String value) {
                                      _password = value;
                                    },
                                    onChanged: (val) {
                                      if (validatePassWord(val) == null) {
                                        setState(() {
                                          passwordIsYes = true;
                                          _password = val;
                                        });
                                      } else {
                                        setState(() {
                                          passwordIsYes = false;
                                        });
                                      }
                                    },
                                    style: TextStyle(
                                        color: passwordIsYes
                                            ? Colors.black
                                            : Colors.red),
                                    validator: validatePassWord,
                                    decoration: InputDecoration(
                                        border: InputBorder.none,
                                        labelText: '请输入密码',
                                        hintText: '请输入密码',
                                        focusColor: Colors.black,
                                        focusedBorder: InputBorder.none,
                                        prefixIcon: Icon(Icons.vpn_key)),
                                  ),
                                  TextFormField(
                                    textInputAction: TextInputAction.done,
                                    //  keyboardType:TextInputType.,
                                    obscureText: true,
                                    validator: regPassword,
                                    onChanged: (val) {
                                      if (regPassword(val) == null) {
                                        setState(() {
                                          repasswordIsYes = true;
                                        });
                                      } else {
                                        setState(() {
                                          repasswordIsYes = false;
                                        });
                                      }
                                    },
                                    style: TextStyle(
                                        color: repasswordIsYes
                                            ? Colors.black
                                            : Colors.red),
                                    decoration: InputDecoration(
                                        border: InputBorder.none,
                                        labelText: '再输入一次密码',
                                        hintText: '再输入一次密码',
                                        focusColor: Colors.black,
                                        focusedBorder: InputBorder.none,
                                        prefixIcon: Icon(Icons.vpn_key)),
                                  ),
                                  TextFormField(
                                    validator: validateCode,
                                    textInputAction: TextInputAction.done,
                                    //  keyboardType:TextInputType.,
                                    // obscureText: true,
                                    onSaved: (code) {
                                      _code = code;
                                    },
                                    inputFormatters:[WhitelistingTextInputFormatter.digitsOnly],//只允许输入数字
                                    decoration: InputDecoration(
                                        border: InputBorder.none,
                                        labelText: '验证码',
                                        suffix: RegFormCode(
                                          available: phoneIsYes,
                                          onTapCallback: (Map val) {
                                            //  if(val["code"]==1&&phoneIsYes){
                                            getCode(_username, context);
                                            //  }
                                          },
                                        ),
                                        focusColor: Colors.black,
                                        focusedBorder: InputBorder.none,
                                        prefixIcon: Icon(Icons.sms_failed)),
                                  )
                                ],
                              ))),
                    ),
                    Offstage(
                      offstage: !isReg,
                      child: Container(
                          padding: EdgeInsets.symmetric(
                              horizontal: ScreenUtil().setWidth(20),
                              vertical: ScreenUtil().setWidth(20)),
                          width: ScreenUtil().setWidth(860),
                          color: Color.fromRGBO(255, 255, 255, 0.7),
                          child: Form(
                              key: _loginKey,
                              child: Column(
                                children: <Widget>[
                                  TextFormField(
                                    textInputAction: TextInputAction.done,
                                    keyboardType: TextInputType.number,
                                    // obscureText: true,
                                    validator: validateUserName,
                                    style: TextStyle(color: Colors.black),

                                    onSaved: (String value) {
                                      _username = value;
                                    },
                                    focusNode: _focusNodeUserName,
                                    decoration: InputDecoration(
                                        border: InputBorder.none,
                                        labelText: '账户',
                                        focusColor: Colors.black,
                                        focusedBorder: InputBorder.none,
                                        prefixIcon: Icon(Icons.people)),
                                  ),
                                  TextFormField(
                                    textInputAction: TextInputAction.done,
                                    //  keyboardType:TextInputType.,
                                    obscureText: true,
                                    onSaved: (String value) {
                                      _password = value;
                                    },

                                    style: TextStyle(color: Colors.black),
                                    validator: validatePassWord,
                                    decoration: InputDecoration(
                                        border: InputBorder.none,
                                        labelText: '请输入密码',
                                        hintText: '请输入密码',
                                        focusColor: Colors.black,
                                        focusedBorder: InputBorder.none,
                                        prefixIcon: Icon(Icons.vpn_key)),
                                  ),
                                ],
                              ))),
                    ),
                    SizedBox(
                      height: ScreenUtil().setHeight(120),
                    ),
                    Offstage(
                        offstage: !isReg,
                        child: RaisedButton(
                          shape: RoundedRectangleBorder(
                              borderRadius:
                                  BorderRadius.all(Radius.circular(50))),
                          onPressed: () {
                           if (_loginKey.currentState.validate()) {
                              _loginKey.currentState.save();
                              login(context);
                            }

                          },
                          child: Container(
                            height: 44.0,
                            width: 240.0,
                            child: Center(
                              child: Text(
                                "登录",
                                style: TextStyle(
                                    fontSize: 15.0,
                                    fontWeight: FontWeight.bold),
                              ),
                            ),
                          ),
                          color: Color(0xffFFDB2E),
                          textColor: Color(0xff202326),
                          elevation: 0.0,
                          focusElevation: 0.0,
                          highlightElevation: 0.0,
                        )),
                    Offstage(
                        offstage: isReg,
                        child: RaisedButton(
                          shape: RoundedRectangleBorder(
                              borderRadius:
                                  BorderRadius.all(Radius.circular(50))),
                          onPressed: () {
                            if (_formKey.currentState.validate()) {
                              _formKey.currentState.save();
                              register(context);
                            }
                          },
                          child: Container(
                            height: 44.0,
                            width: 240.0,
                            child: Center(
                              child: Text(
                                "注册",
                                style: TextStyle(
                                    fontSize: 15.0,
                                    fontWeight: FontWeight.bold),
                              ),
                            ),
                          ),
                          color: Color(0xffFFDB2E),
                          textColor: Color(0xff202326),
                          elevation: 0.0,
                          focusElevation: 0.0,
                          highlightElevation: 0.0,
                        )),
                    Container(
                        width: ScreenUtil().setWidth(600),
                        margin: EdgeInsets.only(top: ScreenUtil().setSp(80)),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: <Widget>[
                            FlatButton(
                              onPressed: () {
                                setState(() {
                                  isReg = !isReg;
                                });
                              },
                              child: Text(
                                "${isReg ? "点击注册" : "返回登录"}",
                                style: TextStyle(color: Colors.blue),
                              ),
                            ),
                            FlatButton(
                              onPressed: () {

                                // info(context);
                              },
                              child: Text(
                                "忘记密码",
                                style: TextStyle(color: Colors.blue),
                              ),
                            ),
                          ],
                        ))
                  ],
                ),
              )
            ],
          ))
        : _loadingContainer;
  }

  final _loadingContainer = Container(
      width: ScreenUtil().setHeight(1080),
      height: ScreenUtil().setHeight(1920),
      constraints: BoxConstraints.expand(),
      color: Colors.black,
      child: Center(
        child: Opacity(
          opacity: 0.9,
          child: SpinKitWave(
            color: Colors.white,
            size: 50.0,
          ),
        ),
      ));

  String validateUserName(value) {
    // 正则匹配手机号

    if (value.isEmpty) {
      return '用户名不能为空!';
    } else if (!RegexUtil.isMobileExact(value)) {
      return '请输入正确手机号';
    }
    return null;
  }

  String validateCode(value) {
    // 正则匹配手机号

    if (value.trim().length != 6) {
      return '验证码错误';
    }
    return null;
  }

  /**
   * 验证密码
   */
  String validatePassWord(value) {
    if (value.isEmpty) {
      return '密码不能为空';
    } else if (value.trim().length < 6 || value.trim().length > 18) {
      return '密码长度不正确';
    }
    return null;
  }

  String regPassword(value) {
    if (value.isEmpty) {
      return '密码不能为空';
    } else if (value != _password) {
      return '密码输入不一致';
    }
    return null;
  }

  getCode(String mobile, context) async {
    await HttpUtil.getInstance()
        .post("/auth/regCaptcha", data: jsonEncode({"mobile": mobile}))
        .then((result) {
      if (result["errno"] != 0) {
        showDialog<Null>(
          context: context,
          barrierDismissible: false,
          builder: (BuildContext context) {
            return new AlertDialog(
              title: new Text('错误'),
              content: new SingleChildScrollView(
                child: new ListBody(
                  children: <Widget>[
                    new Text('${result["errmsg"]}'),
                  ],
                ),
              ),
              actions: <Widget>[
                new FlatButton(
                  child: new Text('确定'),
                  onPressed: () {
                    Navigator.of(context).pop();
                  },
                ),
              ],
            );
          },
        );
      }
    });
  }
 register(context) async {
    await HttpUtil.getInstance()
        .post("/auth/register",
            data: jsonEncode({
              "username": _username,
              "password": _password,
              "mobile": _username,
              "code": _code
            }))
        .then((res) async {
     AuthModel authModel=  AuthModel.fromJson(json.decode(res));
      if (authModel.errno== 0) {
        // AuthModel authModel = AuthModel.fromJson(json.decode(res));
        // SharedPreferences prefs = await SharedPreferences.getInstance();
      _saveString(authModel.data.token, "token");
    Provide.value<AuthProvider>(context).setToken(authModel.data.token);
    Navigator.of(context).pushAndRemoveUntil(
    new MaterialPageRoute(builder: (context)=>HomePage()),
     (route)=>route==null
);
      } else {
    AuthModel authModel=  AuthModel.fromJson(json.decode(res));
        showDialog<Null>(
          context: context,
          barrierDismissible: false,
          builder: (BuildContext context) {
            return new AlertDialog(
              title: new Text('错误'),
              content: new SingleChildScrollView(
                child: new ListBody(
                  children: <Widget>[
                    new Text(authModel.errmsg),
                  ],
                ),
              ),
              actions: <Widget>[
                new FlatButton(
                  child: new Text('确定'),
                  onPressed: () {
                    Navigator.of(context).pop();
                  },
                ),
              ],
            );
          },
        );
      }
    });
  }
  login(context) async {
   await HttpUtil.getInstance()
        .post("/auth/login",
            data: jsonEncode({"username": _username, "password": _password}), )
        .then((res) async {
     AuthModel authModel=  AuthModel.fromJson(json.decode(res));
      if (authModel.errno== 0) {
        // AuthModel authModel = AuthModel.fromJson(json.decode(res));
        // SharedPreferences prefs = await SharedPreferences.getInstance();
      _saveString(authModel.data.token, "token");
      Provide.value<AuthProvider>(context).setToken(authModel.data.token);
     Navigator.of(context).pushAndRemoveUntil(
    new MaterialPageRoute(builder: (context)=>HomePage()),
     (route)=>route==null
);
      } else {
    AuthModel authModel=  AuthModel.fromJson(json.decode(res));
        showDialog<Null>(
          context: context,
          barrierDismissible: false,
          builder: (BuildContext context) {
            return new AlertDialog(
              title: new Text('错误'),
              content: new SingleChildScrollView(
                child: new ListBody(
                  children: <Widget>[
                    new Text(authModel.errmsg),
                  ],
                ),
              ),
              actions: <Widget>[
                new FlatButton(
                  child: new Text('确定'),
                  onPressed: () {
                    Navigator.of(context).pop();
                  },
                ),
              ],
            );
          },
        );
      }
    });
 
  }

}
